package com.hunan.api.catv.service.biz.search;

import com.github.pagehelper.PageInfo;
import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.entity.vo.NewsVo;
import com.hunan.api.catv.service.ResultService;
import com.hunan.api.catv.service.biz.cache.CacheBiz;
import com.hunan.api.catv.service.biz.comment.CommentBiz;
import com.hunan.api.catv.service.biz.news.NewsBiz;
import com.hunan.api.catv.utils.PageUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 搜索
 */
@Service
public class SearchBiz extends ResultService {

    @Autowired
    private SolrClient solrClient;


    @Autowired
    private NewsBiz newsBiz;

    @Autowired
    CommentBiz commentBiz;

    @Autowired
    CacheBiz cacheBiz;

    public ServiceResult init() {
        try {
            String query = "*:*";

            solrClient.deleteByQuery("News", query);
            solrClient.commit("News");


            PageInfo<NewsVo> page = newsBiz.solrList(1, 10, 1);

            int pages = page.getPages();

            UpdateResponse updateResponse = solrClient.addBeans("News", page.getList());
            int status = updateResponse.getStatus();
            if (status != 0) {
                solrClient.rollback();
                return buildFail("批量添加失败");
            } else {
                solrClient.commit("News");
            }
            if (pages > 1) {
                for (int i = 2; i < pages; i++) {
                    PageInfo<NewsVo> pagei = newsBiz.solrList(i, 10, 1);
                    UpdateResponse updateResponseFor = solrClient.addBeans("News", pagei.getList());
                    int statusFor = updateResponseFor.getStatus();
                    if (statusFor != 0) {
                        solrClient.rollback();
                        return buildFail("批量添加失败");
                    } else {
                        solrClient.commit("News");
                    }
                }
            }

        } catch (IOException | SolrServerException e) {
            log.error("Solr Add Error:{}", e);
            return buildFail("批量添加失败");
        }
        return buildOK(true);
    }


    public ServiceResult add(NewsVo newsVo) {
        try {
            UpdateResponse updateResponse = solrClient.addBean("News", newsVo);
            int status = updateResponse.getStatus();
            if (status != 0) {
                solrClient.rollback();
                return buildFail("添加失败");
            } else {
                solrClient.commit("News");
            }
        } catch (IOException | SolrServerException e) {
            log.error("Solr Add Error:{}", e);
            return buildFail("添加失败");
        }
        return buildOK(true);
    }

    public ServiceResult del(Integer newsId) {
        try {
            UpdateResponse updateResponse = solrClient.deleteById("News", newsId.toString());
            int status = updateResponse.getStatus();
            if (status != 0) {
                solrClient.rollback();
                return buildFail("删除失败");
            } else {
                solrClient.commit("News");
            }
        } catch (IOException | SolrServerException e) {
            log.error("Solr Add Error:{}", e);
            return buildFail("删除失败");
        }
        return buildOK(true);
    }

    public PageInfo<NewsVo> list(String key, Integer pageNum, Integer pageSize) {
        SolrQuery query = new SolrQuery();
        query.setQuery("title:" + key + " OR tags:" + key);
//		query.add("q","title:"+key);
        query.setStart((pageNum - 1) * pageSize);
        query.setRows(pageSize);
        query.setSort("id", SolrQuery.ORDER.asc);

        QueryResponse response = null;
        try {
            response = solrClient.query("News", query);

        } catch (SolrServerException | IOException e) {
            log.error("SOLR:{}", e);
        }

        //查询到的记录总数
        int totalRow = Long.valueOf(response.getResults().getNumFound()).intValue();
        //查询结果集
        List<NewsVo> searchList = response.getBeans(NewsVo.class);
        List<NewsVo> newsList = new ArrayList<>();
        int len = searchList.size();
        for (int i = 0; i < len; i++) {
            NewsVo newsVo = searchList.get(i);
            //NewsVo newsVo2 = newsBiz.getById(newsVo.getNewsId());
            NewsVo newsVo2 = newsBiz.getNewsInfo(newsVo.getNewsId());
            if (newsVo2 != null) {
                BeanUtils.copyProperties(newsVo2, newsVo);
                newsVo.setCommentVo(commentBiz.getHotCommentsByNewsId(newsVo.getNewsId()));
                newsList.add(newsVo);
            }
        }
//		PageInfo<NewsVo> pageInfo = new PageInfo<NewsVo>(newsList);
//		pageInfo.setPageNum(pageNum);
//		pageInfo.setPageSize(pageSize);
//		pageInfo.setTotal(totalRow);
        return PageUtils.list2PageInfoForSearch(pageNum, pageSize, newsList, totalRow);
    }


    public static String format(Integer count) {
        if (count < 10000) {
            return String.valueOf(count);
        }
        if (count % 10000 == 0) {
            return count / 10000 + "w";
        }
        double c = Double.valueOf(count + ".0");
        return String.format("%.1f", c / 10000) + "w";
    }
}
